﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.IO;
using System.Xml.Serialization;

namespace Server.ProjectHelpers
{
    public class ProjectController
    {
        protected Dictionary<int, ProjectDecorator> _projects;
        protected ServerDataBaseContainer _connection;

        public void AddObserver(int projectId, GUI.ProjectObserver observer)
        {
            ProjectDecorator project;
            if (_projects.TryGetValue(projectId, out project))
            {
                project.OnChange += new EventHandler(observer.ProjectOnChange);
                observer.ProjectOnChange(project, EventArgs.Empty);
            }

        }

        public void AddNew(string name)
        {
            if(_connection.ProjectSet.Any(p => p.Name == name)){
                throw new Exception("Projekt juz istnieje");
            }
            XmlSerializer configReader = new XmlSerializer(typeof(Config));
            string projectPath = Path.Combine(Environment.CurrentDirectory, ConfigurationSettings.AppSettings["ProjectPath"], name);
            using (Stream file = File.OpenRead(Path.Combine(projectPath, "project.xml")))
            {
                Config config = (Config)configReader.Deserialize(file);
                var project = new Project
                {
                    AddDate = DateTime.Now,
                    Name = config.Name,
                    Status = _connection
                        .ProjectStatusSet
                        .Where(s => s.Id == (int)ProjestStatuses.Active)
                        .First(),
                    MaxDaysOfCompiuting = config.MaxDaysOfCompiuting
                };
                _connection.ProjectSet.AddObject(project);
                _connection.SaveChanges();

                var decorator = new ProjectDecorator(project.Id, project.Name);
                _projects.Add(project.Id, decorator);
            }
        }

        public void RemoveProject(int id)
        {
            var project = _connection.ProjectSet.First(p => p.Id == id);
            _projects.Remove(id);
            string projectPath = Path.Combine(Environment.CurrentDirectory, ConfigurationSettings.AppSettings["ProjectPath"], project.Name);
            System.IO.DirectoryInfo directory = new System.IO.DirectoryInfo(projectPath);
            foreach (System.IO.FileInfo file in directory.GetFiles()) file.Delete();
            foreach (System.IO.DirectoryInfo subDirectory in directory.GetDirectories()) subDirectory.Delete(true);
            _connection.ProjectSet.DeleteObject(project);
            _connection.SaveChanges();
        }

        public byte[] GetParamiter(int projectId, int parameterId, bool IsDynamic)
        {
            /*var computing = _connection
                .CompiutingSet
                .First(c => c.Id == computingId);

                computing.Paramiters
                .First(p => p.ParameterPleace == parameterPleace);
                var project = computing.Project;*/
            return _projects[projectId].Lib.GetParamiter(parameterId, IsDynamic);
        }

        public LibInterface.Compiuting RequestCompiutingData(int projectId)
        {
            var project = _connection.ProjectSet.First(p => p.Id == projectId);
            var projektLib = _projects[projectId];

            LibInterface.Compiuting data = projektLib.GetDataToCompiuting();
            data.ProjectId = projectId;
            return data;



        }

        public ProjectController()
        {

            _connection = new ServerDataBaseContainer();
            _projects = new Dictionary<int, ProjectDecorator>();
            var data = _connection
                .ProjectSet
                .Where(p => p.Status.Id == (int)ProjestStatuses.Active)
                .ToList();
            foreach (var item in data)
            {
                var project = new ProjectDecorator(item.Id, item.Name);
                _projects.Add(item.Id, project);
            }
        }

        public List<Services.DTO.ProjectFilesDTO> GetProjectFiles(int projectId)
        {
            string name = _connection.ProjectSet.First(p => p.Id == projectId).Name;
            string projectPath = Path.Combine(Environment.CurrentDirectory, ConfigurationSettings.AppSettings["ProjectPath"], name);
            List<Services.DTO.ProjectFilesDTO> fileList = new List<Services.DTO.ProjectFilesDTO>();
            Config config;
            XmlSerializer configReader = new XmlSerializer(typeof(Config));
            using (Stream file = File.OpenRead(Path.Combine(projectPath, "project.xml")))
            {
                config = (Config)configReader.Deserialize(file);
            }

            foreach (string file in config.ClientLibFiles)
            {
                string path = Path.Combine(projectPath, file);
                fileList.Add(new Services.DTO.ProjectFilesDTO
                {
                    ProjectId = projectId,
                    Path = file,
                    File = GetBytesFromFile(path)
                });
            }
            return fileList;

        }

        private static byte[] GetBytesFromFile(string fullFilePath)
        {

            FileStream fs = File.OpenRead(fullFilePath);
            try
            {
                byte[] bytes = new byte[fs.Length];
                fs.Read(bytes, 0, Convert.ToInt32(fs.Length));
                fs.Close();
                return bytes;
            }
            finally
            {
                fs.Close();
            }

        }
    }
}
